{% extends 'project/layout.html' %}
{% load static %}
{% block title %}
项目管理
{% endblock%}
{% block css%}
<style>
  .title{
    display: flex;
    justify-content: space-between;
  }
  .error{
      position: absolute;
      color: red;
  }
</style>

{% endblock %}
{% block content %}

      <div class="panel panel-default">
          <!-- Default panel contents -->
          <div class="panel-heading title">
                <ol class="breadcrumb" style="margin: 0;padding: 0;">
                  <li><a href="{% url 'web:file' project_id=request.tracer.project.id %}">文件库</a></li>
                  {% for item in breadcrumb%}

                  <li><a href="">{{item.name}}</a></li>
<!--                  <li class="active">Data</li>-->
                  {% endfor %}
                </ol>
            <div style="display: flex;align-items: center">
                <button id="newFileFold"
                    type="button"
                    class="btn btn-info"
                    data-toggle="modal" data-target="#myModal"
                    style="margin-right: 10px"
                >新建文件夹</button>
                <input id="newFile"
                    type="file"
                    name="uploadFiles"
                    multiple
                    ></input>
            </div>

          </div>
          <div class="panel-body">
                <!-- Table -->
                <table class="table">
<!--                <caption>Optional table caption.</caption>-->
                <thead>
                <tr>
                  <th>文件名</th>
                  <th>文件大小</th>
                  <th>更新者</th>
                  <th>更新时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {% for item in file_list %}
                    <tr>

                      {% if item.file_type == 1 %}
                        <th scope="row"><i class="iconfont icon-caidan"></i> {{item.name}}</th>
                          <td>{{item.file_size}}</td>
                      {% else %}
                        <th scope="row">
                            <a href="{% url 'web:file' project_id=request.tracer.project.id %}?folder={{item.id}}">
                                <i class="iconfont icon-wenjianjia"></i> {{item.name}}
                            </a>
                        </th>
                         <td>-</td>
                      {% endif %}
                      <td>{{item.update_user.username}}</td>
                      <td>{{item.update_datetime}}</td>
                     {% if item.file_type == 1 %}
                      <td>
                           <button type="button"
                                   class="btn btn-success btn-xs down"
                                   data-id="{{item.id}}"
                           >下载
                           </button>
                          <button type="button"
                                  class="btn btn-danger btn-xs delA"
                                  data-id="{{item.id}}"
                                  data-toggle="modal" data-target="#alertModal"

                          >删除</button>
                      </td>
                      {% else %}
                         <td>
                           <button type="button"
                                   class="btn btn-info btn-xs edit"
                                   data-toggle="modal" data-target="#myModal"
                                   data-id="{{item.id}}"
                                   data-name="{{item.name}}"

                           >编辑
                           </button>
                          <button type="button"
                                  class="btn btn-danger btn-xs delA"
                                  data-id="{{item.id}}"
                                  data-toggle="modal" data-target="#alertModal"

                          >删除</button>
                      </td>
                      {% endif %}
                    </tr>
                {% endfor %}

              </tbody>
            </table>
        </div>
      </div>
<!--文件cos上传进度显示-->
  <div class="result">

  </div>
  <!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        <form id="createForm">
          {% csrf_token %}
          {% for item in form %}
              <input  style="visibility: hidden" id="id_id"  name="id" >
              <div class="form-group">
                <label for="{{item.id_for_label}}">{{item.label}}</label>
                {{ item }}
                  <span class="error">{{item.errors.0}}</span>
              </div>
          {% endfor %}
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="save">确定</button>
      </div>
    </div>
  </div>
</div>
<!--删除模态框-->
<div class="modal fade" id="alertModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">

        <div class="alert alert-danger alert-dismissible fade in" role="alert">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4>是否确定要删除!</h4>
          <p>文件夹以及子文件夹内容都会被删除!</p>
          <p style="text-align: right">
            <button type="button" data-dismiss="modal" class="btn btn-default">取消</button>
            <button  id="delBtn" type="button" class="btn btn-danger " data-id="">确定</button>

          </p>
        </div>

<!--    </div>-->
  </div>
</div>
{% endblock%}

{% block js %}
<script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
<script>
    var pre = document.querySelector('.result');
    var showLogText = function (text, color) {
        if (typeof text === 'object') {
            try {
                text = JSON.stringify(text);
            } catch (e) {
            }
        }
        var div = document.createElement('div');
        div.innerText = text;
        color && (div.style.color = color);
        pre.appendChild(div);
        pre.style.display = 'block';
        pre.scrollTop = pre.scrollHeight;
    };
    var logger = {
    log: function (text) {
        console.log.apply(console, arguments);
        var args = [].map.call(arguments, function (v) {
            return typeof v === 'object' ? JSON.stringify(v, null, 2) : v;
        });

        var logStr = args.join(' ');

        if(logStr.length > 1000000) {
            logStr = logStr.slice(0, 1000000) + '...content is too long, the first 1000000 characters are intercepted';
        }

        showLogText(logStr);
    },
    error: function (text) {
        console.error(text);
        showLogText(text, 'red');
    },
};
//获取临时凭证 用于cos的上传
const COS_OBJECT=new COS({
    getAuthorization: function (options, callback) {
         $.get('{% url "web:cos" project_id=request.tracer.project.id %}', {
                    }, function (res) {
             if(res.status){
                                        let credentials =res.data && res.data.credentials;
                                        callback({
                                            TmpSecretId: credentials.tmpSecretId,
                                            TmpSecretKey: credentials.tmpSecretKey,
                                            XCosSecurityToken: credentials.sessionToken,
                                            StartTime: res.data.startTime,
                                            ExpiredTime: res.data.expiredTime
                                        });
                                    }else{
                  alert(res.error);
             }
             })
    }
})
  //新建文件夹
  function addFileFold(){
    let fileFoldDoc=document.querySelector("#newFileFold")
    fileFoldDoc.addEventListener('click',(e)=>{
      document.querySelector('#myModalLabel').innerText='添加文件夹'
      document.querySelector('#createForm').reset()
    })
  }
  addFileFold()
  //保存添加文件夹
  function save(){
      const saveBtn =document.querySelector('#save')
      saveBtn.addEventListener('click', async (e) => {
          let form=document.querySelector('#createForm')
          let formData = new FormData(form)
           // {% url "web:file" project_id=request.tracer.project.id %}
          const res=await fetch(location.href,{
              method : 'POST',
              body:formData
          })
          const data=await res.json()
          if(data.code ===200){
              location.reload()
          }else{
                for(let item in data.error){
                    // console.log(item)
                    let doc=document.querySelector(`#id_${item}`)
                    // console.log(doc)

                    doc.nextElementSibling.innerText=data.error[item]
                }
          }
      })
  }
  save()
  //编辑文件夹
  function editFileFold(){
    let fileFoldDoc=document.querySelectorAll(".edit")
      for (let item of fileFoldDoc) {
          item.addEventListener('click',(e)=>{
          document.querySelector('#myModalLabel').innerText='编辑文件夹'
          document.querySelector('#createForm').reset()
          document.querySelector('#id_name').value=e.target.dataset.name
          document.querySelector('#id_id').value=e.target.dataset.id
    })
      }

  }
  editFileFold()
  //每一行的删除 按钮
  function delA(){
      const delAll=document.querySelectorAll('.delA')
      for (let item of delAll) {
          item.addEventListener('click', (e) => {
              let id=e.target.dataset.id //文件|文件夹id
              let delbtn=document.querySelector('#delBtn')
              delbtn.dataset.id=id
          })
      }
  }
  delA()
  //删除文件夹
  function deleteFileFold(){
    let delbtn=document.querySelector('#delBtn')
    delbtn.addEventListener('click', async (e) => {
        let file_id=e.target.dataset.id
        const res=await fetch(`{% url "web:file_delete" project_id=request.tracer.project.id %}?id=${file_id}`,{
            method:'get',

        })
        const data=await res.json()
        if(data.code==200){
            location.reload()
        }else{
            console.log(code.error)
            alert('删除失败')
        }
    })
  }
  deleteFileFold()
  //点击上传文件
  function uploadFile(){
      const uploadBtn=document.querySelector('#newFile')
      uploadBtn.addEventListener('change', async (e)=>{
          let fileslist= [] //获取上传文件的格式，上传的文件列表
          let checkList=[] // 检查文件大小是否超出限制
          for(let item of uploadBtn.files){
              let temp={
                        Bucket: '{{ request.tracer.project.bucket }}', // Bucket 格式：test-1250000000
                        Region: '{{ request.tracer.project.region }}',
                        Key: `${(new Date()).getTime()}_${item.name}`,
                        name:item.name,
                        Body: item,
                        size:item.size
                    }
              fileslist.push(temp)
              checkList.push({name:item.name,size:item.size})
            }
          //检查上传的文件大小
          const res=await http({
              method : 'POST',
              url:'{% url "web:file_check" project_id=request.tracer.project.id %}',
              data:checkList
          })
          //文件大小限制 退出函数执行
          if(res.code===400) return alert(res.error)
          //循环上传文件
          COS_OBJECT.uploadFiles({
                    files:fileslist,
                    SliceSize: 1024 * 1024,
                    onProgress: function (info) {
                        var percent = Math.floor(info.percent * 10000) / 100;
                        var speed = Math.floor(info.speed / 1024 / 1024 * 100) / 100;
                        logger.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
                    },
                    onFileFinish: function (err, data, options) {

                        logger.log(options.Key + ' 上传' + (err ? '失败' : '完成'));
                    },
                },  async function (err, data) {
                    // logger.log('uploadFiles:', err || data);
                    // console.log(data)
                    // console.log(fileslist)
                    //获取文件列表
                    if(data){
                        let filelist=[]
                        for(let item of data.files){
                            if(item.data.statusCode==200){
                                filelist.push({Key:item.options.Key,bucket:item.options.Bucket,Region:item.options.Region,})
                            }
                        }
                        // console.log(data.files)
                        //后台更新 项目使用的空间 && 更新文件 数据库
                        const res=await http({
                            method : 'POST',
                            url :'{% url "web:file_upload" project_id=request.tracer.project.id %}?folder={{folder.id}}',
                            // url :location.href,
                            data : fileslist
                        })
                        console.log(res)
                    }
                });
          //上传文件结尾
      })
  }
  uploadFile()
  // 下载文件
  function downLoadFile(){
    let downbtns=document.querySelectorAll('.down')
    for(let item of downbtns){
        item.addEventListener('click',(e)=>{
            let file_id=e.target.dataset.id
            let url=`{% url 'web:file_download' project_id=request.tracer.project.id %}?id=${file_id}`
            console.log(url)
            location.href=url
        })
    }
  }
  downLoadFile()
</script>

{% endblock%}